<?php

namespace App\Console\Commands\Init;

use App\Console\BaseCommand;
use App\Consts\GlobalConst;
use App\Models\SysArticle;
use App\Models\User;

/**
 * 【V2.0.5】用户初始化脚本
 * Class ArticleCounterCommand
 * @package App\Console\Scripts\Counter
 */
class UserInitCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'init:user {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'init user info';

    /**
     * 用户地址初始化
     * @return int
     */
    public function address()
    {
        $subMode = $this->_getSubModel();
        $finish = $subMode->count();
        // 每 100 单位合并处理一次
        $subMode->chunkById(100, function ($list) use ($finish) {
            foreach ($list as $item) {
                static $index = 1;
                $id = $item->user_id;
                $address = $item->address;
                $res = $address;
                if ($res) {
                    // 用户地址中的 - 替换为 ,
                    $address = str_replace('-', ',', $address);
                    // 把地址中的省、大陆去掉
                    $address = str_replace('省', '', $address);
                    $address = str_replace('大陆', '', $address);
                    User::getModel()->where('user_id', $id)->update(['address' => $address]);
                    $info = "[$index/$finish] update data to `user` {$id} - " . $address;
                } else {
                    $info = "[$index/$finish] check data - user_id - " . $id;
                }
                // log info
                $this->info($info);
                if ($res) $this->logger($info, false, 'script');
                $index++;
            }
        }, 'user_id');
        return 1;
    }

    /**
     * get sub model
     * @return SysArticle|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed
     */
    private function _getSubModel()
    {
        $subMode = User::getModel()
            ->select(['id', 'user_id', 'address'])
            ->where('is_deleted', GlobalConst::IS_NOT_DELETE);
        return $subMode;
    }

}
